// 导入db模块
const db = require('../common/db/index')
// 获取当前时间的函数
const { getCurrentTime } = require('../common/javascript/index')

//如果不是好友关系，就执行==0的逻辑
// status： 1    发送加好友的请求
// status： 2    已同意
// status： -1   已拒绝

// 定义通讯录类
class Friend {
    // 添加
    add(user_id, friend_id) {
        // YYYY-MM-DD hh:mm:ss
        let create_at = getCurrentTime()// 时间
        return new Promise((resolve, reject) => {
            db.query(`select status from pre_friends where user_id = '${user_id}' and friend_id='${friend_id}'`)
                .then(
                    rows => {
                        // console.log("2--->",rows)
                        if (rows.length == 0) {
                            db.query(`insert into pre_friends(user_id, friend_id, status, create_at) values('${user_id}','${friend_id}','1','${create_at}')`)
                                .then(
                                    () => {
                                        resolve({
                                            code: 200,
                                            msg: "发送加友好的请求",
                                        })
                                    }
                                )
                                .catch(
                                    err => {
                                        // console.log("3:--->",err)
                                        reject({
                                            code: 500,
                                            msg: "后台发生异常",
                                            err
                                        })
                                    }
                                )
                        }
                        else {
                            let status = rows[0] && rows[0].status
                            resolve({
                                code: 1,
                                msg: status == 1 ? "已发送添加好友请求,等待对方同意" : "已添加好友",
                                status
                            })
                        }
                    }
                )
                .catch(
                    err => {
                        // console.log("1:--->",err)
                        reject({
                            code: 500,
                            msg: "后台发生异常",
                            err
                        })
                    }
                )
        })
    }
    //查询
    // 查看请求通知
    async  notice(user_id) {
        let arr = [];
         // 别人是否给自己发送请求
        await db.query(`select * from pre_friends where  status=1 and friend_id ='${user_id}' `)
         .then(
             rows => {
                 if (rows.length != 0 ) {
                    arr.push(... rows)
                 }
             }
         )

        //  自己是否给别人发送的请求
        // await  db.query(`select * from pre_friends where  status=1 and user_id='${user_id}' `)
        //  .then(
        //      rows => {
        //          if (rows.length != 0) {
        //             arr.push(... rows)
        //          }
        //      }
        //  )
        return new Promise((resolve, reject) => {
              resolve({
                code: 200,
                result: [... arr]
              })
        })
    }

    // 编辑请求状态
    async modify(user_id, friend_id, status) {
         let isHas = true;
         let message = ""
         // 别人是否给自己发送请求
         await  db.query(`select * from pre_friends where friend_id='${user_id}' and user_id='${friend_id}'`)
         .then(
             rows => {
                 if (rows.length == 1) {
                    isHas = true;
                 }
                
             }
         )
         .catch(
             err => {
                console.log(err)
             }
         )

         // 自己是否给别人发送请求
         await  db.query(`select * from pre_friends where friend_id='${friend_id}' and user_id='${user_id}'`)
         .then(
             rows => {
                 if (rows.length == 1) {
                    isHas = true;
                 }
             }
         )
         .catch(
             err => {
                console.log(err)
             }
         )


        if(isHas) {
           await  db.query(`update pre_friends set status= '${status}' where friend_id='${user_id}' and user_id='${friend_id}'`)
            .then(
                content => {
                    if(content.fieldCount === 0) {
                        message = status == 2 ? '同意' : '拒绝'
                    }
                }
            )

            await  db.query(`update pre_friends set status= '${status}' where friend_id='${friend_id}' and user_id='${user_id}'`)
            .then(
                content => {
                    if(content.fieldCount === 0) {
                        message = status == 2 ? '同意' : '拒绝'
                    }
                }
            )
        }


        return new Promise((resolve, reject) => {
             resolve({
                code: message == '同意' ? 200 : -1,
                msg: "已处理请求,"+message
             })
        })
        
    }
    // 查看好友列表
    async  list(id) {
        let arr = []
       // 别人添加自己成为的好友
       await  db.query(`select * from pre_friends where  status='2' and friend_id ='${id}' or  status='2' and user_id ='${id}'`)
        .then(
            rows => {
                arr.push(... rows)
            }
        )
        .catch(
            err => {
                console.log(err)
            }
        )
        // 自己添加别人成为的好友
        //    await  db.query(`select * from pre_friends where status='2' and user_id ='${id}'`)
        //    .then(
        //        rows => {
        //            arr.push(... rows)
        //        }
        //    )
        //    .catch(
        //        err => {
        //         console.log(err)
        //        }
        //    )


        return new Promise((resolve, reject) => {
            resolve({
                code: 200,
                msg: "好友列表",
                result: [... arr]
            })
        })
    }
    //删除
    async remove(user_id, friend_id) {
        let isRemove = false;
        let isFriend = false;
        //自己添加别人的好友关系
        await db.query(`select status from pre_friends where user_id = '${user_id}' and friend_id='${friend_id}' and status='2'`)
        .then(
            rows => {
                if (rows.length == 1) {
                    isFriend = true;
                }
            }
        )
        .catch(
            err => {
                console.log(err)
            }
        )

         //别人添加自己的好友关系
         await db.query(`select status from pre_friends where user_id = '${friend_id}' and friend_id='${user_id}' and status='2'`)
         .then(
             rows => {
                 if (rows.length == 1) {
                     isFriend = true;
                 }
             }
         )
         .catch(
             err => {
                console.log(err)
             }
         )


        if(isFriend) {
            //自己添加别人的好友关系
            await db.query(`delete from pre_friends where user_id = '${user_id}' and friend_id='${friend_id}' `)
            .then(
                content => {
                    if(content.changedRows === 0){
                        isRemove = true;
                    }
                }
            )
            .catch(
                err => {
                    console.log(err)
                }
            )

            //别人添加自己的好友关系
            await db.query(`delete from pre_friends where user_id = '${friend_id}' and friend_id='${user_id}' `)
            .then(
                content => {
                    if(content.changedRows === 0){
                        isRemove = true;
                    }
                }
            )
            .catch(
                err => {
                    console.log(err)
                }
            )
        }
        return new Promise((resolve, reject) => {
            resolve({
                code: isRemove == true ? 200: -1,
                msg: isRemove == true ? "删除好友成功":"删除好友失败"
            })
        })
    }
    // 判断是否为好友关系
    async is_friend(user_id, friend_id) {
        // console.log({user_id, friend_id})
        let isHas = false;
        await db.query(`select * from pre_friends where user_id = '${user_id}' and friend_id='${friend_id}'`)
            .then(
                rows => {
                    if (rows.length == 1) {
                        isHas = true;
                    }
                }
            )

        await db.query(`select * from pre_friends where user_id = '${friend_id}' and friend_id='${user_id}'`)
            .then(
                rows => {
                    if (rows.length == 1) {
                        isHas = true;
                    }
                }
            )

            // console.log({isHas})
        return new Promise((resolve,reject)=>{
            resolve({
                code: isHas == true ? 200: -1,
                msg: isHas == true ? "好友关系":"非好友关系"
            })
        })
    }

    
}

// 把通讯录（好友）类的实例挂在模块系统对象上
module.exports = Friend;